import { defaultStorage as store } from '../infra/storage.mjs'
import Koa from 'koa'

export const auth: Koa.Middleware = async (ctx, next) => {
  let token = ctx.get('Authorization')
  if (!token) {
    ctx.status = 401
    ctx.body = {
      success: false,
      msg: '未授权',
      data: null
    }
    return
  }

  if (token.startsWith('Bearer')) {
    token = token.substring(6).trim()
  }

  if (!token) {
    ctx.status = 401
    ctx.body = {
      success: false,
      msg: '未授权',
      data: null
    }
    return
  }

  const user = await store.getUserByToken(token)
  if (!user) {
    ctx.status = 401
    ctx.body = {
      success: false,
      msg: '未授权',
      data: null
    }
    return
  }

  ctx.state.user = user
  await next()
}
